VERSION 0.8
FROM node:20
WORKDIR /contrib/web

src-files:
  COPY ../config+src-files/* ../config
  COPY package.json .
  COPY pnpm-lock.yaml .

api-files:
  COPY geo/world.geojson ./geo/world.geojson
  COPY public/locales/en.json ./public/locales/en.json
  SAVE ARTIFACT .

prepare:
  FROM +src-files
  RUN npm install -g pnpm@9
  RUN pnpm install --frozen-lockfile
  COPY index.html .postcssrc.json tailwind.config.cjs tsconfig.json tsconfig.node.json vite.config.ts .
  COPY scripts/generateZonesConfig.ts ./scripts/generateZonesConfig.ts
  COPY scripts/register-tsNodeESM.js ./scripts/register-tsNodeESM.js
  COPY scripts/generateSitemap.js ./scripts/generateSitemap.js
  COPY --dir geo public src ./

test:
  FROM +prepare
  COPY ../+linting-files/* ../
  COPY .gitignore .eslintrc.json .prettierrc.json viteEnvironment.d.ts testSetup.ts .
  COPY --dir cypress ./
  RUN pnpm run create-generated-files
  RUN pnpm run validate
  # TODO: Enable Cypress tests later
  # RUN pnpm run cy:test-all

build-staging:
  FROM +prepare
  RUN pnpm run create-generated-files
  RUN pnpm version minor
  RUN --secret SENTRY_AUTH_TOKEN --secret VITE_PUBLIC_ELECTRICITYMAP_PUBLIC_TOKEN_V9=ELECTRICITYMAPS_APP_PUBLIC_TOKEN_V9 --secret VITE_POSTHOG_KEY=API_PORTAL_POSTHOG_KEY_STAGING pnpm run build

  # Local outputs for debugging
  SAVE ARTIFACT ./config/world.json AS LOCAL ./config/world.json
  SAVE ARTIFACT ./config/usa_states.json AS LOCAL ./config/usa_states.json
  SAVE ARTIFACT ./config/excluded_aggregated_exchanges.json AS LOCAL ./config/excluded_aggregated_exchanges.json
  # NOTE: We could consider dropping source maps from dist since it has already been uploaded to Sentry at this point
  SAVE ARTIFACT ./dist AS LOCAL ./dist

build:
  FROM +prepare
  RUN pnpm run create-generated-files
  RUN pnpm version minor
  RUN --secret SENTRY_AUTH_TOKEN --secret VITE_PUBLIC_ELECTRICITYMAP_PUBLIC_TOKEN_V9=ELECTRICITYMAPS_APP_PUBLIC_TOKEN_V9 --secret VITE_POSTHOG_KEY=API_PORTAL_POSTHOG_KEY pnpm run build

  # Local outputs for debugging
  SAVE ARTIFACT ./config/world.json AS LOCAL ./config/world.json
  SAVE ARTIFACT ./config/usa_states.json AS LOCAL ./config/usa_states.json
  SAVE ARTIFACT ./config/excluded_aggregated_exchanges.json AS LOCAL ./config/excluded_aggregated_exchanges.json
  # NOTE: We could consider dropping source maps from dist since it has already been uploaded to Sentry at this point
  SAVE ARTIFACT ./dist AS LOCAL ./dist

deploy-staging:
  FROM +prepare
  COPY +build-staging/dist ./dist
  RUN npm install -g wrangler
  RUN --push --secret CLOUDFLARE_API_TOKEN --secret CLOUDFLARE_ACCOUNT_ID wrangler pages deploy ./dist --project-name electricitymaps-staging --branch main

deploy:
  FROM +prepare
  COPY +build/dist ./dist
  RUN npm install -g wrangler
  RUN --push --secret CLOUDFLARE_API_TOKEN --secret CLOUDFLARE_ACCOUNT_ID wrangler pages deploy ./dist --project-name electricitymaps-app --branch master
